package com.wyl.auth.Interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.wyl.auth.config.security.SecurityHolder;
import com.wyl.auth.config.security.SecurityUser;
import com.wyl.auth.entity.SysUser;
import com.wyl.auth.service.SysUserService;
import com.wyl.auth.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author WuYiLong
 * @Date 2025/4/16 22:02
 */
@Component
public class SecurityInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object userId = StpUtil.getLoginIdDefaultNull();
        if(userId != null) {
            Object object = redisTemplate.opsForValue().get(userId.toString());
            SysUser sysUser;
            if(object == null) {
                sysUser = sysUserService.getById(Long.valueOf(userId.toString()));
                redisTemplate.opsForValue().set(userId, sysUser);
            }
            sysUser = (SysUser) object;
            if(sysUser != null) {
                SecurityUser securityUser = new SecurityUser();
                securityUser.setUserId(sysUser.getId());
                securityUser.setUsername(sysUser.getUsername());
                SecurityHolder.setUser(securityUser);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SecurityHolder.clear();
    }
}